require("dotenv").config();
const express = require("express");
const app = express();
const cors = require("cors");
const PORT = process.env.PORT;
const requestUser = require("./utils/user");
app.use(express.static("public"));
app.use(express.json());
app.use(cors());
app.get("/", (req, res) => {
  res.send("vue3 admin server is running...");
});
app.listen(PORT, () => {
  console.log(`server is running on port ${PORT}`);
});

app.get("/api/users/:id", (req, res) => {
  const { id } = req.params;
  requestUser.getUserById(id).then((data) => {
    res.json({
      code: 200,
      message: "success",
      data: data,
    });
  });
});

app.post("/api/hasUser", (req, res) => {
  const { username, password } = req.body;
  requestUser.hasUser({ username, password }).then((data) => {
    res.json({
      code: 200,
      message: "success",
      data: data,
    });
  });
});

app.post("/api/addUser", (req, res) => {
  const body = req.body;
  requestUser.addUser(body).then((data) => {
    if (typeof data === "string") {
      res.json({
        code: 500,
        message: data,
        data: null,
      });
    } else {
      res.json({
        code: 200,
        message: "success",
        data: data,
      });
    }
  });
});
